from random import randint

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from .serializer import RegisterSMSCodeSerializer
from libs.captcha.captcha import captcha
from libs.yuntongxun.sms import CCP


class RegisterImage(APIView):
    #图片验证码
    #GET verifications/imagercodes/(?P<image_code_id>.+)/
    def get(self,request,image_code_id):
        #通过第三方库获取图片验证码
        #通过redis保存验证，加配置文件
        #创建图片的验证码captcha会返回text，和image
        text,image=captcha.generate_captcha()
        print(text)
        #通过redis进行保存验证码
        redis_conn=get_redis_connection('imagecode')
        redis_conn.setex('image_%s'%image_code_id,120,text)
        #将图片返回
        #图片是二进制，我们通过HttpResponse
        return HttpResponse(image,content_type='image/jpeg')



class RegisterSMScode(GenericAPIView):
    #获取短信验证码
    #GET/verifications/smscodes/(?P<mobile>1[345789]\d{9})/?text=xxxx & image_code_id=xxxx
    #创建序列化器，定义text 和image_code_id
    #redis判断该用户是否频繁获取
    # 生成短信验证码
    #redis增加记录
    #发送短信
    #返回响应
    serializer_class = RegisterSMSCodeSerializer

    def get(self,request,mobile):
        #创建序列化器，定义text和image_code_id
        serializer=self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)
        #redis
        redis_conn=get_redis_connection('imagecode')
        #判断该用户是否频繁获取
        if redis_conn.get('sms_flag_%s' %mobile):
            return Response(status=status.HTTP_429_TOO_MANY_REQUESTS)
        #生成短信验证码
        sms_code='%06d'%randint(0,999999)
        print(sms_code)
        #redis增加记录
        redis_conn.setex('sms_%s'%mobile,5*60,sms_code)
        redis_conn.setex('sms_flag_%s'%mobile,60,1)
        #发送短信
        # ccp=CCP()
        # #
        # ccp.send_template_sms(mobile,[sms_code,5],1)

        #每次需要celery导入任务  需要用函数名.delay进行队列任务添加（对应的参数需要传过来）
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile,sms_code)


        #返回响应
        return Response({'message':'ok'})
